﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Com.Framework
{
	public static class ParseUtil
	{
		public static TReturnType Do<TSourece, TReturnType>(this TSourece obj, Func<TSourece, TReturnType> action)
		{
			return action(obj);
		}

		public static T Parse<T>( this object obj )
		{
			return obj.Parse( default(T) );
		}

		public static T Parse<T>( this object obj, T defaultVal)
		{
			try
			{
				if (defaultVal is Enum)
				{
					if (obj is string)
					{
						return (T)Enum.Parse(typeof(T), obj.ToString());
					}
					else
					{
						return (T)obj;
					}
				}
				else if (defaultVal is string)
				{
					if (!string.IsNullOrEmpty((string)Convert.ChangeType(obj, typeof(T))))
						return (T)Convert.ChangeType(obj, typeof(T));
				}
				else if (defaultVal == null)
				{
					return (T)obj;
				}
				else
				{
					return (T)Convert.ChangeType(obj, typeof(T));
				}
			}
			catch (Exception)
			{
			}

			return defaultVal;
		}

		public static string HTMLEncode(this string str)
		{
			return System.Web.HttpContext.Current.Server.HtmlEncode(str);
		}

		public static string ReplaceBRTag(this string str)
		{
			return str.Replace("\n", "<br/>");
		}
	}
}
